<!DOCTYPE html>
<html lang="en-us">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="This is meta description">
  <meta name="generator" content="Hugo 0.74.3" />
  <title>欢迎来到中国非物质文化遗产论坛</title>

  <!-- Vue and Axios -->
  <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>

  <!-- Plugins -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0-alpha1/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/themify-icons/0.1.2/css/themify-icons.css">

  <!-- Main Stylesheet -->
  <link rel="stylesheet" href="css/style.css" media="screen">
  <script src="./js/axios.js"></script>
  
  <!-- Favicon -->
  <link rel="shortcut icon" href="images/favicon.png" type="image/x-icon">
  <link rel="icon" href="images/favicon.png" type="image/x-icon">

  <!-- Meta Tags -->
  <meta property="og:title" content="中国非物质文化遗产论坛" />
  <meta property="og:description" content="欢迎加入中国非物质文化遗产论坛" />
</head>
<body>

<!-- Navigation -->
<header class="navigation">
    <div class="container" id="index">
      <nav class="navbar navbar-expand-lg navbar-white">
        <a class="navbar-brand order-1" href="index.html">
          <img class="img-fluid" width="50px" src="images/图标.png"
            alt="中国传统文化论坛">
        </a>
        <div class="collapse navbar-collapse text-center order-lg-2 order-3" id="navigation">
          <ul class="navbar-nav mx-auto">
            <li class="nav-item active">
              <a class="nav-link" href="index.html">首页</a>
            </li>
            <li class="nav-item @@about__active">
              <a class="nav-link" href="BBS_index.html">论坛</a>
            </li>
            <li class="nav-item @@services__active">
              <a class="nav-link" href="chat.html">消息</a>
            </li>
            <li class="nav-item @@services__active">
              <a class="nav-link" href="shop.html">商店</a>
            </li>
          </ul>
        </div>
        <div class="order-2 order-lg-3 d-flex align-items-center">
          <form @submit.prevent="performSearch"> <!-- 阻止表单提交 -->
            <input 
              id="search-query" 
              name="s" 
              type="search" 
              placeholder="输入文章ID"
              v-model="searchId" 
            >
            <button type="submit" class="btn btn-search">搜索</button>
          </form>
          <button class="navbar-toggler border-0 order-1" type="button" data-toggle="collapse" data-target="#navigation">
            <i class="ti-menu"></i>
          </button>
          <ul class="navbar-nav ml-auto" v-if="userid==null">
            <li class="nav-item @@login__active">
                <a class="nav-link" href="Login.html">登录</a>
            </li>
            <li class="nav-item @@register__active">
                <a class="nav-link" href="register.html">注册</a>
            </li>
        </ul>
        <ul class="navbar-nav ml-auto 1ogined" v-else>
            <li class="nav-item @@login__active">
              <span><a class="nav-link" href="person-post.html">{{userid}}</a></span>
            </li>
            <li class="nav-item @@register__active">
                <span v-on:click.prevent="logout"><a class="nav-link" href="BBS_index.html">注销</a></span>
            </li>
        </ul>
        </div>
      </nav>
    </div>
  </header>
    <!--/MENU-JS-->
    <script>
        new Vue({
          el: "#index",
          data: {
            userid: localStorage["userid"],
            searchId: '' // 用于存储搜索的ID
          },
          methods: {
            logout: function() {
              localStorage.clear();
              this.userid = null;
            },
            performSearch: function() {
              if (!this.searchId || this.searchId.trim() === '') {
                // 如果为空，跳转到404页面
                alert("请输入文章id");
                return;
              }
              // 存储搜索ID到localStorage
              localStorage.setItem("num", this.searchId);
              // 跳转到post.html
              location.href = "post.html";
            }
          }
        })
    </script>

<!-- Main Content -->
<div id="app" class="container-fluid">
  <div class="row" style="height: 80vh;">
    <!-- Sidebar (Contacts) -->
    <div class="col-md-3 col-12 sidebar">
      <h5 class="text-center">联系人</h5>
      <a href="chatlist.html"><button class="btn btn-look">查看用户拉黑情况</button></a>
      <div class="contact-list">
        <div class="contact" v-for="contact in contacts" :key="contact.id" @click="setCurrentChat(contact.id)">
          用户 {{ contact.id }}
          <span class="unread-count" v-if="unreadCounts[contact.id] > 0" >{{ unreadCounts[contact.id] }}</span>
        </div>
      </div>
    </div>

    <!-- Chat Area -->
    <div class="col-md-9 col-12 chat-area">
      <div class="chat-box">
        <div v-for="(message, index) in messages" :key="index" :class="['message', message.senderId === Number(userId) ? 'my_message' : 'frnd_message']">
          <div  :class="['message', message.senderId === Number(userId) ? 'message-content' : 'frnd_message_content']">
            <p> {{ message.text }}<br> <span>{{message.timestamp}} </span></p>
            <div v-if="message.senderId === Number(userId)" class="read-status">
              <div v-if="message.isRead">已读</div>
              <div v-else>未读</div>
            </div>
            <a v-if="message.senderId === Number(userId)" @click="revokeMessage(message.messageId)">撤回</a> 
          </div>
        </div>
      </div>
      <div class="input-area">
        <input 
          v-model="newMessage" 
          type="text" 
          class="form-control message-input" 
          placeholder="输入消息..."
          @keydown.enter="sendMessage" />
        <button class="btn btn-primary send-btn" @click="sendMessage">发送</button>
      </div>
    </div>
    
  </div>
</div>

<!-- Footer -->
<footer class="footer text-center py-4 mt-5">
  <p>&copy; 2024 中国非物质文化遗产论坛 | All Rights Reserved</p>
</footer>

<script>
  new Vue({
    el: '#app',
    data: {
      unreadCounts: {},
      userid: localStorage["userid"],
      searchId: '',
      userId: 1, // 当前用户的 ID
      contacts: [
        { id: 2 },
        { id: 3 },
        { id: 4 },
      ],
      currentChatId: null, // 当前聊天对象的 ID
      messages: [],
      newMessage: '',
      isSentByUser:false
    },
    methods: {
      logout() {
        localStorage.clear();
        this.userid = null;
      },
      // 获得侧边栏的user
      async getMessagesByUsers(userId) {
          try {
            this.userId = localStorage["userid"]
            const response = await axios.get(`https://localhost:7071/api/Message/user/${this.userId}`);
            // 获取消息数据
            const messages = response.data;

            // 提取所有的 senderId 和 receiverId
            const senderIds = messages.map(message => message.senderId);
            const receiverIds = messages.map(message => message.receiverId);
            // 打印提取的 senderId 和 receiverId（或根据需求处理）
            console.log("Sender IDs:", senderIds);  // 输出所有发送者ID
            console.log("Receiver IDs:", receiverIds);  // 输出所有接收者ID
            
            // 合并 senderId 和 receiverId 数组，并去重，排除当前用户的 userId
            const uniqueIds = [...new Set([...senderIds, ...receiverIds])]
              .filter(id => Number(id) !== Number(this.userId));  // 强制转换为相同类型

            // 输出去重并过滤后的唯一用户 ID
            console.log("Unique User IDs (excluding current user):", uniqueIds);

            // 将 uniqueIds 转换为 { id: X } 格式
            const contacts = uniqueIds.map(id => ({ id }));

            // 输出最终格式化的 contacts
            console.log("Contacts:", contacts);

            // 存储格式化后的 contacts
            this.contacts = contacts;
                } catch (error) {
                  console.error('Error fetching messages:', error);
                }
              },
             
      performSearch() {
        if (!this.searchId || this.searchId.trim() === '') {
          location.href = "404.html";
          return;
        }
        localStorage.setItem("num", this.searchId);
        location.href = "post.html";
      },
      setCurrentChat(contactId) {
        this.currentChatId = contactId;
        this.getMessagesBetweenUsers(contactId);
      },

      //获得两边的 messsage
      async getMessagesBetweenUsers(contactId) {
        try {
          const userId = localStorage["userid"]; // 获取当前用户的 ID
          const response = await axios.get(`https://localhost:7071/api/Message/between/${userId}/${contactId}`);
          // 处理消息列表，判断每条消息的发送方是否是当前用户
          this.messages = response.data.map(message => ({
            ...message,
            messageId: message.messageId,
            timestamp: new Date(message.timestamp).toLocaleString(), // 格式化时间
            isSentByUser: message.senderId === Number(userId), // 判断消息是否由当前用户发送
            messagePosition: message.senderId === Number(userId) ? 'my_message' : 'frnd_message', // 根据发送方设置消息位置
          }),
          console.log(userId),
          console.log(this.messages))
          // 调用消息更新后，滚动到最底部
          this.$nextTick(() => {
            this.scrollToBottom(); // 确保滚动到页面底部
          });
          this.getMessagesByUsersNum(userId);
          this.getMessagesByUsers(userId);
        } catch (error) {
          console.error('Error fetching messages:', error);
        }
      },
      
      // 发送消息
      async sendMessage() {
        if (this.newMessage.trim()) {
          const newMsg = {
            messageId: 0,
            senderId: this.userId, // 当前用户的 ID
            receiverId: this.currentChatId, // 选择的用户的 ID
            text: this.newMessage, // 输入框中的消息内容
            timestamp: new Date().toISOString(), // 获取当前时间戳（ISO 格式）
            isRead: false, // 默认消息未读
          };
          console.log(newMsg.timestamp);
          try {
            const userId = localStorage["userid"];
            // 先调用 isBlocked API 判断是否被禁言
            const isBlockedResponse = await axios.get(`https://localhost:7071/api/Message/isBlocked/${this.currentChatId}/${this.userId}`);
            console.log(isBlockedResponse)
            if (isBlockedResponse.data === true) {
              alert('你已被对方拉黑，无法发送消息');
              this.newMessage = ''; // Clear input
              this.getMessagesBetweenUsers(this.currentChatId);
            } else {
            // 发送 POST 请求到后端
            const response = await axios.post('https://localhost:7071/api/Message', newMsg);
            if (response.data!=null) {
              // 如果发送成功，将消息加入消息列表
              this.messages.push({
                ...newMsg,
                timestamp: new Date().toLocaleString(), // 格式化时间（显示为本地时间）
                isSentByUser: newMsg.senderId === Number(userId), // 判断消息是否由当前用户发送
                messageId: response.data,
              });
              this.newMessage = ''; // Clear input
              console.log('Message sent successfully');
              this.getMessagesBetweenUsers(this.currentChatId);
            }
          } }catch (error) {
            console.error('Error sending message:', error);
          }
        }
      },

      // 撤回消息
      async revokeMessage(messageId) {
        try {
          console.log(messageId);
          var userId = localStorage.getItem("userid");  // 获取当前用户的 ID
          const response = await axios.delete(`https://localhost:7071/api/Message/${messageId}/${userId}`);
          if (response.data) {
            // 如果返回值为 true，撤回成功，执行相应操作（如更新消息列表）
            console.log("消息撤回成功");
            // 更新 UI：例如，删除本地消息列表中的这条消息
            this.messages = this.messages.filter(message => message.messageId !== messageId);
          } else {
            // 如果返回值为 false，撤回失败，执行相应操作
            alert("消息撤回失败");
            console.log("消息撤回失败");
          }
          } catch (error) {
            console.error("撤回消息时发生错误", error);
          }
      },

        // 获取
        async getMessagesByUsersNum(userId) {
          try {
            this.userId = localStorage["userid"];
            const response = await axios.get(`https://localhost:7071/api/Message/unread/${this.userId}`);
            const unreadMessages = response.data;

            // 更新 unreadCounts
            this.unreadCounts = unreadMessages.reduce((counts, messageGroup) => {
              messageGroup.forEach(message => {
                if (!counts[message.senderId]) {
                  counts[message.senderId] = 0;
                }
                if (!message.isRead) {
                  counts[message.senderId]++;
                }
              });
              return counts;
            }, {});

            // 提取所有的 senderId 和 receiverId
            const senderIds = unreadMessages.flatMap(group => group.map(msg => msg.senderId));
            const receiverIds = unreadMessages.flatMap(group => group.map(msg => msg.receiverId));
            const uniqueIds = [...new Set([...senderIds, ...receiverIds])]
              .filter(id => Number(id) !== Number(this.userId));

            // 将 uniqueIds 转换为 { id: X } 格式
            const contacts = uniqueIds.map(id => ({ id }));

            // 存储格式化后的 contacts
            this.contacts = contacts;
          } catch (error) {
            console.error('Error fetching messages:', error);
          }
        },
    async getMessagesBetween(userId, contactId) {
      const response = await axios.get(`https://localhost:7071/api/Message/between/${userId}/${contactId}`);
      return response.data;
    },
    updateMessageId(timestamp, messageId) {
        const message = this.messages.find(msg => msg.timestamp === timestamp);
        if (message) {
          message.messageId = messageId;
        }
      },
      scrollToBottom() {
        const chatBox = document.querySelector('.chat-box');
        chatBox.scrollTop = chatBox.scrollHeight;
      }
    },
    mounted() {
      // this.setCurrentChat(this.contacts[0].id); 
      this.getMessagesByUsersNum(this.userId);
      this.getMessagesByUsers(this.userid);
    }
  });
</script>

<!-- jQuery & Bootstrap -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0-alpha1/js/bootstrap.bundle.min.js"></script>

<style>
  .sidebar {
    position: relative;
    background-color: #f9f9f9;
    padding: 15px;
    border-right: 1px solid #ddd;
    overflow-y: auto;
  }

  .sidebar h5 {
    font-size: 1.2rem;
    color: #333;
  }

  .contact-list {
    padding: 10px;
  }

  .contact {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px;
  margin-bottom: 8px;
  background-color: #f1f1f1;
  cursor: pointer;
  border-radius: 5px;
  transition: background-color 0.3s ease;
}

  .contact:hover {
    background-color: #e0e0e0;
  }

  .chat-area {
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
  height: 100%;
}

.chat-box {
    position: relative;
    width: 100%;
    height: calc(100%-120px);
    padding: 50px;
    overflow-y: auto;
    /* background-color: #e0e0e0; */
}

.message{
    position: relative;
    display: flex;
    width: 100%;
    margin: 5px 0;
    /* flex-direction: column; */
}

.message-content {
  width: 50%; /* 控制整个消息容器的宽度 */
  justify-content: flex-end; /* 使内容在容器内向右对齐 */
  display: flex;
  flex-direction: column; /* 使内容垂直排列 */
  align-items: flex-end; /* 使 p 标签右对齐 */
}

.frnd_message_content {
  width: 50%;
  justify-content: flex-start;
  display: flex;
  flex-direction: column;  /* 让内容垂直排列 */
  align-items: flex-start; /* 使 p 标签右对齐 */
}
.message p {
  position: relative;
  max-width: 80%; /* 最大宽度限制 */
  padding: 12px;
  background: #dcf8c6;
  border-radius: 10px;
  font-size: 0.9em;
  display: inline-block; /* 根据内容自适应宽度 */
  word-wrap: break-word; /* 防止长单词溢出 */
  flex-direction: column; /* 将内容竖直排列 */
}

.message p::before {
    content: '';
    position: absolute;
    top: 0;
    right: -12px;
    width: 20px;
    height: 20px;
    background: linear-gradient(135deg, #dcf8c6 0%, #dcf8c6 50%, transparent 50%, transparent);
}

.message p span {
    margin-top: 5px;
    font-size: 0.85em;
    opacity: 0.5;
}
.message a {
  margin-top: 5px;
  font-size: 0.85em;
  opacity: 0.5;
  cursor: pointer;
}
.my_message
{
    justify-content: flex-end;
}
.frnd_message
{
    justify-content: flex-start;
    width:100%
}
.frnd_message p
{
    background: #f9b9b9;
    text-align: left;
}

.message.frnd_message p::before
{
    content: '';
    position: absolute;
    top: 0;
    left: -12px;
    width: 20px;
    height: 20px;
    background: linear-gradient(225deg,#f9b9b9 0%,#f9b9b9 50%,transparent 50%,transparent);
}



.input-area {
  display: flex;
  align-items: center;
  padding: 10px;
}

.message-input {
  flex-grow: 1;
  margin-right: 10px;
  padding: 10px;
  border-radius: 20px;
  border: 1px solid #ccc;
}

.send-btn {
  padding: 10px 10px;
  border-radius: 20px;
  border: none;
  background-color: #007bff;
  color: white;
  cursor: pointer;
  font-size: 12px;
  /* 默认情况下，文字就是横向排列的 */
}

.send-btn:hover {
  background-color: #0056b3;
}
.read-status {
  opacity: 0.5;
  font-size: 12px;
  color: #888; /* 设置状态文字颜色为灰色 */
  margin-left: 10px; /* 让状态文字和消息之间有一定的间距 */
}
.unread-count {
  display: inline-block;
  background-color: red;
  color: white;
  font-size: 12px;
  font-weight: bold;
  padding: 2px 8px;
  border-radius: 50%;
  margin-left: 5px;
}
</style>

</body>
</html>
